import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:signature/signature.dart';
import 'package:flutter/services.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

import '../../../route/route_utils.dart';

class SignatureBoard extends StatefulWidget {
  final double aspectRatio; // 固定宽高比
  final Color? penColor;
  final double penStrokeWidth;

  const SignatureBoard({
    super.key,
    this.aspectRatio = 16 / 9,
    this.penColor,
    this.penStrokeWidth = 5.0,
  });

  @override
  State<SignatureBoard> createState() => _SignatureBoardState();
}

class _SignatureBoardState extends State<SignatureBoard> {
  late SignatureController _controller;
  final List<List<Point>> _undoStack = [];
  final List<List<Point>> _redoStack = [];

  @override
  void initState() {
    super.initState();
    // 进入页面自动横屏
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]);

    // 固定画笔颜色和导出图片颜色
    _controller = SignatureController(
      penStrokeWidth: widget.penStrokeWidth,
      penColor: Colors.black,
      exportBackgroundColor: Colors.white,
      onDrawStart: () {
        _redoStack.clear();
      },
      onDrawEnd: () {
        _undoStack.add(List.from(_controller.points));
      },
    );
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // 固定画笔颜色和导出图片颜色
    _controller = SignatureController(
      penStrokeWidth: widget.penStrokeWidth,
      penColor: Colors.black,
      exportBackgroundColor: Colors.white,
      onDrawStart: () => _redoStack.clear(),
      onDrawEnd: () => _undoStack.add(List.from(_controller.points)),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    // 离开页面恢复竖屏
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
    super.dispose();
  }

  void _undo() {
    if (_undoStack.isNotEmpty) {
      _redoStack.add(_undoStack.removeLast());
      _controller.points = _undoStack.expand((e) => e).toList();
      setState(() {});
    }
  }

  void _redo() {
    if (_redoStack.isNotEmpty) {
      _undoStack.add(_redoStack.removeLast());
      _controller.points = _undoStack.expand((e) => e).toList();
      setState(() {});
    }
  }

  Future<void> _submit() async {
    if (_controller.isEmpty) {
      ScaffoldMessenger.of(context)
          .showSnackBar(const SnackBar(content: Text('请先签名')));
      return;
    }

    // 1. 导出为 PNG 字节
    Uint8List? data = await _controller.toPngBytes();
    if (data == null || data.isEmpty) {
      ScaffoldMessenger.of(context)
          .showSnackBar(const SnackBar(content: Text('签名导出失败')));
      return;
    }

    try {
      // 1. 构造 MultipartFile
      final file = MultipartFile.fromBytes(data, filename: 'signature.png');
      // 2. 构造 FormData
      final formData = FormData.fromMap({'file': file});
      // 3. 上传
      // await ApiWaterQuality.api.uploadSignature(formData);
      if (mounted) {
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text("上传成功")));
        RouteUtils.pop(context);
      }
    } catch (e) {
      debugPrint('签名上传失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text("上传失败")));
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    final cs = Theme.of(context).colorScheme;
    final isDark = Theme.of(context).brightness == Brightness.dark;

    return Scaffold(
      appBar: AppBar(
        title: Text(l10n.signatureTitle),
        backgroundColor: cs.surface,
        elevation: 0.5,
        actions: [
          IconButton(
            tooltip: l10n.commonUndo,
            onPressed: _undo,
            icon: Icon(Icons.undo, color: cs.primary),
          ),
          IconButton(
            tooltip: l10n.commonRedo,
            onPressed: _redo,
            icon: Icon(Icons.redo, color: cs.primary),
          ),
          IconButton(
            tooltip: l10n.commonClear,
            onPressed: () => _controller.clear(),
            icon: Icon(Icons.clear, color: cs.error),
          ),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 8.0),
            child: ElevatedButton.icon(
              style: ElevatedButton.styleFrom(
                backgroundColor: cs.primary,
                foregroundColor: cs.onPrimary,
              ),
              onPressed: _submit,
              icon: const Icon(Icons.check),
              label: Text(l10n.commonSave),
            ),
          ),
        ],
      ),
      body: Center(
        child: AspectRatio(
          aspectRatio: widget.aspectRatio,
          child: Container(
            margin: const EdgeInsets.all(8.0),
            padding: const EdgeInsets.all(8.0),
            decoration: BoxDecoration(
              color: isDark ? cs.surfaceContainerHighest : Colors.white,
              border: Border.all(color: cs.outline),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Signature(
              controller: _controller,
              backgroundColor:
                  isDark ? cs.surfaceContainerHighest : Colors.white,
            ),
          ),
        ),
      ),
    );
  }
}
